package com.tensquare.article.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.tensquare.article.pojo.Article;
import com.tensquare.article.service.ArticleService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("article")
@CrossOrigin
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    //测试公共异常
    @RequestMapping(value = "exception",method = RequestMethod.GET)
    public Result test(){
        int a=1/0;
        return null;
    }
    //post/article/search/{page}/{size}文章分页
    @RequestMapping(value = "search/{page}/{size}",method = RequestMethod.POST)
    //所有条件进行判断
    //使用集合遍历
    public Result findByPage(@PathVariable Integer page,
                             @PathVariable Integer size,
                             @RequestBody Map<String,Object> map){
        //根据条件分页查询
       Page<Article> pageData =  articleService.findByPage(map,page,size);
       //封装分页对象
        PageResult<Article> pageResult =new PageResult<>(
                pageData.getTotal(),pageData.getRecords()
        );
       //返回数据
        return new Result(true,StatusCode.OK,"查询成功",pageResult);

    }
    //DELETE/article/{articleId} 根据id删除文章
    @RequestMapping(value = "{articleId}",method = RequestMethod.DELETE)
    public Result deleteById(@PathVariable String articleId){
        articleService.deleteById(articleId);
        return new Result(true,StatusCode.OK,"删除成功");
    }
    //post/article 增加文章
    @RequestMapping(method = RequestMethod.POST)
    public Result save(@RequestBody Article article){
        articleService.save(article);
        return new Result(true,StatusCode.OK,"新增成功");
    }
    // get/article/{article} 根据id查询文章
    @RequestMapping(value = "{articleId}",method = RequestMethod.GET)
    public Result findById(@PathVariable String articleId){
        Article article =articleService.findById(articleId);
        return new Result(true,StatusCode.OK,"查询成功",article);



    }
    //get/article 文章全部列表
    @RequestMapping(method = RequestMethod.GET)
    @GetMapping("/findAll")
    public Result findAll(){
        List<Article> list=articleService.findAll();
        return new Result(true,StatusCode.OK,"查询成功",list);
    }
}
